package com.zggk.lzz.lzmlbj2;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.matisse.Matisse;
import com.zggk.lzz.R;
import com.zggk.lzz.adapter.LGRecycleViewAdapter;
import com.zggk.lzz.adapter.LGViewHolder;
import com.zggk.lzz.api.MyApplication;
import com.zggk.lzz.api.Urls;
import com.zggk.lzz.lzmladd.LzmlAddJson;
import com.zggk.lzz.lzmladd.LzmlRoadBean;
import com.zggk.lzz.lzmlbj.LzmlJsBean;
import com.zggk.lzz.mvp.MVPBaseActivity;
import com.zggk.lzz.util.NoRecycleView;
import com.zggk.lzz.util.NoScroolGridView;
import com.zggk.lzz.util.Utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class LzmlBj2Activity extends MVPBaseActivity<LzmlBj2Contract.View, LzmlBj2Presenter> implements LzmlBj2Contract.View {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.cancle_button)
    TextView cancleButton;
    @Bind(R.id.lxbm_et)
    TextView lxbmEt;
    @Bind(R.id.lxbm_lay)
    LinearLayout lxbmLay;
    @Bind(R.id.zhwz_et)
    TextView zhwzEt;
    @Bind(R.id.sjlx_et)
    TextView sjlxEt;
    @Bind(R.id.sjlx_lay)
    LinearLayout sjlxLay;
    @Bind(R.id.xcfw_re)
    NoRecycleView xcfwRe;
    @Bind(R.id.sjzt_te)
    EditText sjztTe;
    @Bind(R.id.sjzt_lay)
    LinearLayout sjztLay;
    @Bind(R.id.rydh_et)
    EditText rydhEt;
    @Bind(R.id.ldmm_et)
    TextView ldmmEt;
    @Bind(R.id.add_pic_grid)
    NoScroolGridView addPicGrid;
    @Bind(R.id.add_pic_lay)
    LinearLayout addPicLay;
    @Bind(R.id.save_te)
    TextView saveTe;
    @Bind(R.id.activity_disease_new_scrollview)
    ScrollView activityDiseaseNewScrollview;
    @Bind(R.id.disease_new_parent_layout)
    RelativeLayout diseaseNewParentLayout;
    private LzmlJsBean.DataBean dataBeans;
    private List<String> JsDatas = new ArrayList<>();
    private LzmlBjGird lzmlBjGird;
    private Map<Integer, LzmlBjGird> mapAdapter = new HashMap<>();
    private List<LzmlRoadBean.DataBean.RecordsBean> AdapterDatas = new ArrayList<>();
    private LGRecycleViewAdapter<LzmlRoadBean.DataBean.RecordsBean> adapter;
    private List<LzmlRoadBean.DataBean.RecordsBean> RoadDatas = new ArrayList<>();
    private List<String> RoadData = new ArrayList<>();
    private OptionsPickerView pickerView;
    private OptionsPickerView pickerView2;
    private LzmlJsBean.DataBean.RecordsBean dataBean;
    private int REQUEST_CODE_CHOOSE = 66;
    private int childViewPosition;//点击拍照获取的childveiw下标
    private LzmlJs2Bean.DataBean dataInfo;

    public void setChildViewPosition(int childViewPosition) {
        this.childViewPosition = childViewPosition;
    }



    @Override
    public void onRequestError(String msg) {

    }

    @Override
    protected int getLayout() {
        return R.layout.act_lzml_add;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        initData();
        initAdapter();
    }

    private void initData() {
        mPresenter.getData2(LzmlBj2Activity.this);

    }

    @Override
    public void getDatas(LzmlJs2Bean.DataBean dataBean1) {
        this.dataInfo=dataBean1;
        for (int i = 0; i < dataBeans.getRecords().size(); i++) {
            if (dataBeans.getRecords().get(i).getId().equals(dataBean1.getRecords().getRoadModel())){
                lxbmEt.setText(dataBeans.getRecords().get(i).getRoleName());
                dataBean = dataBeans.getRecords().get(i);
            }
        }
        if (dataBean1.getRecords().getRoadIdList()!=null){
            List<String> roadIdList = new ArrayList<>();
            roadIdList =  Arrays.asList(dataBean1.getRecords().getRoadIdList().split(","));
            for (int i = 0; i < RoadDatas.size(); i++) {
                for (int j = 0; j < roadIdList.size(); j++) {
                    if (RoadDatas.get(i).getId().equals(roadIdList.get(j))){
                        AdapterDatas.add(RoadDatas.get(i));
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        }

        zhwzEt.setText(MyApplication.spUtils.getString("UserName"));
        sjztTe.setText(dataBean1.getRecords().getAdministratorNameName());
        rydhEt.setText(dataBean1.getRecords().getPhone());
        ArrayList<Drawable> listPicture = new ArrayList<>();
        ArrayList<String> listImgUrl = new ArrayList<>();
        if (dataBean1.getRecords().getPic()!=null&&dataBean1.getRecords().getPic().size()>0) {
            for (int i = 0; i < dataBean1.getRecords().getPic().size(); i++) {
                final String sss = Urls.JAVASERVER + "pms/rhms/lzzapp/getImage?id=" + dataBean1.getRecords().getPic().get(i).getPicId() + "&token=Bearer$" + MyApplication.spUtils.getString("Token");
                listImgUrl.add(sss);
                Drawable drawable = new BitmapDrawable();
                listPicture.add(drawable);
            }
        }
        Drawable addPicture = getResources().getDrawable(R.drawable.img_add_pic);
        listPicture.add(addPicture);
        final int childPosition = addPicLay.getChildCount();
        lzmlBjGird = new LzmlBjGird(this, listPicture, listImgUrl, childPosition);
        addPicGrid.setAdapter(lzmlBjGird);
        mapAdapter.put(childPosition, lzmlBjGird);
    }

    @Override
    public void getData2s(LzmlJsBean.DataBean dataBean) {
        this.dataBeans = dataBean;
        for (int i = 0; i < dataBean.getRecords().size(); i++) {
            JsDatas.add(dataBean.getRecords().get(i).getRoleName());
        }
        mPresenter.getData3(LzmlBj2Activity.this);
    }

    @Override
    public void getData3s(LzmlRoadBean.DataBean dataBean) {
        this.RoadDatas=dataBean.getRecords();
        for (int i = 0; i < dataBean.getRecords().size(); i++) {
            RoadData.add(dataBean.getRecords().get(i).getRoad_name());
        }
        mPresenter.getData(getIntent().getStringExtra("Id"),LzmlBj2Activity.this);
    }

    @Override
    public void addData4s() {
        finish();
    }

    private void initAdapter() {
        xcfwRe.setHasFixedSize(true);
        xcfwRe.setNestedScrollingEnabled(false);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        xcfwRe.setLayoutManager(manager);
        adapter = new LGRecycleViewAdapter<LzmlRoadBean.DataBean.RecordsBean>(AdapterDatas) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_lzml_add;
            }

            @Override
            public void convert(final LGViewHolder holder, LzmlRoadBean.DataBean.RecordsBean zCDBean, final int position) {
                holder.setText(R.id.lxmc_te, zCDBean.getRoad_name());
                holder.setText(R.id.lxbm_te, zCDBean.getRoad_code());
                TextView de_img = (TextView) holder.getView(R.id.de_img);
                de_img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AdapterDatas.remove(holder.getAdapterPosition());
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        };
        xcfwRe.setAdapter(adapter);
    }
    @OnClick({R.id.lxbm_lay, R.id.sjlx_lay, R.id.save_te})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.lxbm_lay:
                pickerView = new OptionsPickerView.Builder(LzmlBj2Activity.this, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        lxbmEt.setText(JsDatas.get(options1));
                        dataBean = dataBeans.getRecords().get(options1);
                    }
                }).setLayoutRes(R.layout.progress_lay, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        TextView ivCancel = (TextView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pickerView.returnData();
                                pickerView.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pickerView.dismiss();
                            }
                        });
                    }
                }).build();
                pickerView.setPicker(JsDatas);
                pickerView.show();
                break;
            case R.id.sjlx_lay:
                pickerView2 = new OptionsPickerView.Builder(LzmlBj2Activity.this, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        AdapterDatas.add(RoadDatas.get(options1));
                        adapter.notifyDataSetChanged();
                    }
                }).setLayoutRes(R.layout.progress_lay, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        TextView ivCancel = (TextView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pickerView2.returnData();
                                pickerView2.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pickerView2.dismiss();
                            }
                        });
                    }
                }).build();
                pickerView2.setPicker(RoadData);
                pickerView2.show();
                break;
            case R.id.save_te:
                if (lxbmEt.getText().toString().equals("请选择")) {
                    ToastUtils.showShort("请选择路长角色");
                    return;
                }
                if (Utils.isNull(rydhEt.getText().toString())) {
                    ToastUtils.showShort("请输入电话号码");
                    return;
                }
                if (AdapterDatas.size() == 0) {
                    ToastUtils.showShort("请添加路线");
                    return;
                }
                LzmlBjJson recordsBean = new LzmlBjJson();
                recordsBean.setId(dataInfo.getRecords().getId());
                recordsBean.setAdministratorName(MyApplication.spUtils.getString("UserID"));
                recordsBean.setRoadModel(dataBean.getId());
                recordsBean.setOrgId(MyApplication.spUtils.getString("OrgId"));
                recordsBean.setOrgName(MyApplication.spUtils.getString("OrgName"));
                recordsBean.setPhone(rydhEt.getText().toString());
                List<String> roadIdList = new ArrayList<>();
                for (int i = 0; i < AdapterDatas.size(); i++) {
                    roadIdList.add(AdapterDatas.get(i).getId());
                }
                recordsBean.setRoadIdList(roadIdList);
                recordsBean.setLzOrgId(MyApplication.spUtils.getString("OrgId"));
                recordsBean.setLzOrgName(MyApplication.spUtils.getString("OrgName"));
                recordsBean.setAdministratorNameName(sjztTe.getText().toString());
                String imgStr2 = "";
                ArrayList<String> listImgUrl2 = lzmlBjGird.getListImgUrl();
                if (listImgUrl2 != null && listImgUrl2.size() > 0) {
                    for (int k = 0; k < listImgUrl2.size(); k++) {
                        if (k == 0) {
                            imgStr2 += listImgUrl2.get(k);
                        } else {
                            imgStr2 += "," + listImgUrl2.get(k);
                        }
                    }
                }
                if (!StringUtils.isSpace(imgStr2)) {
                    String[] strArr = imgStr2.split(",");
                    if (strArr != null && strArr.length > 0) {
                        ArrayList<LzmlBjJson.PICBean> listPic = new ArrayList<>();
                        for (int i = 0; i < strArr.length; i++) {
                            LzmlBjJson.PICBean picInfo = new LzmlBjJson.PICBean();
                            String imgUrl = strArr[i];
                            String nameStr = imgUrl.substring(imgUrl.lastIndexOf("/") + 1, imgUrl.length());
                            picInfo.setPicFileName(nameStr);
                            String strBlob = Utils.bmpToBase64String(imgUrl);
                            picInfo.setPicDataBlob(strBlob);
                            listPic.add(picInfo);
                        }
                        recordsBean.setPIC(listPic);
                    }
                }
                String sss = JSON.toJSONString(recordsBean);
                mPresenter.addData4(sss, LzmlBj2Activity.this);
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            final LzmlBjGird lzmlBjGird = mapAdapter.get(childViewPosition);
            final ArrayList<Drawable> listPicture = lzmlBjGird.getListPicture();
            final ArrayList<String> listImgUrl = lzmlBjGird.getListImgUrl();
            String imgPath = Matisse.obtainCropResult(data);
            listPicture.remove(listPicture.size() - 1);
            Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
            if (bitmap != null) {
                Drawable drawable = new BitmapDrawable(bitmap);
                listPicture.add(drawable);
                listImgUrl.add(imgPath);
                Drawable addPicture = getResources().getDrawable(R.drawable.img_add_pic);
                listPicture.add(addPicture);
                lzmlBjGird.notifyDataSetChanged();
            }
        }
    }
}
